#!/bin/bash

# 短信验证平台启动脚本 - 宝塔Linux面板11.1.0专用版本
# 完全兼容宝塔Linux面板11.1.0环境，优化了权限管理和错误处理

# 脚本颜色配置
GREEN="\033[0;32m"
YELLOW="\033[1;33m"
RED="\033[0;31m"
BLUE="\033[0;34m"
NC="\033[0m" # No Color

# 定义变量
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="$PROJECT_DIR/logs"
DIAGNOSTIC_LOG="$LOG_DIR/startup_diagnostics.log"
GUNICORN_ERROR_LOG="$LOG_DIR/gunicorn_error.log"
GUNICORN_ACCESS_LOG="$LOG_DIR/gunicorn_access.log"
VENV_DIR="$PROJECT_DIR/venv"
PYTHON_VERSION="3.7"
PORT=8091
WORKERS=4
TIMEOUT=60

# 显示启动信息
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}🎯 短信验证平台 - 宝塔Linux面板11.1.0专用启动脚本${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}$(date +"%Y-%m-%d %H:%M:%S") - 启动脚本开始执行${NC}"

# 确保日志目录存在并设置权限
setup_log_directory() {
    echo -e "${BLUE}[宝塔适配] 创建并设置日志目录...${NC}"
    mkdir -p "$LOG_DIR"
    chmod 755 "$LOG_DIR"
    
    # 宝塔特定：设置www用户权限
    if id "www" &>/dev/null; then
        chown www:www "$LOG_DIR"
        echo -e "${GREEN}[宝塔适配] 已设置日志目录所有权为www:www${NC}"
    fi
    
    # 清空诊断日志
    > "$DIAGNOSTIC_LOG"
    echo -e "${GREEN}[宝塔适配] 日志目录初始化完成${NC}"
}

# 记录日志到文件和控制台
log_message() {
    local level=$1
    local message=$2
    local timestamp=$(date "%Y-%m-%d %H:%M:%S")
    local color=$NC
    
    case $level in
        "INFO") color=$BLUE ;;
        "WARN") color=$YELLOW ;;
        "ERROR") color=$RED ;;
        "SUCCESS") color=$GREEN ;;
    esac
    
    echo -e "$timestamp [$level] $message" >> "$DIAGNOSTIC_LOG"
    echo -e "${color}[$level] $message${NC}"
}

# 检查宝塔环境
detect_baota_environment() {
    log_message "INFO" "检测宝塔面板环境..."
    
    # 检查是否在Windows环境中运行
    if [[ "$OSTYPE" == "msys"* ]] || [[ "$OSTYPE" == "win"* ]] || [[ -n "$WINDIR" ]]; then
        log_message "ERROR" "此脚本专为Linux宝塔面板设计，无法在Windows环境中运行"
        echo -e "${RED}❌ 错误: 请在Linux服务器的宝塔面板环境中运行此脚本${NC}"
        echo -e "${YELLOW}提示: Windows环境下请使用start_gunicorn.bat脚本${NC}"
        exit 1
    fi
    
    # 检查是否在宝塔默认目录结构
    if [[ "$PROJECT_DIR" == "/www/wwwroot/"* ]]; then
        log_message "SUCCESS" "在宝塔标准目录结构中运行"
        BAOTA_ENV="true"
    else
        log_message "WARN" "不在宝塔标准目录结构中运行，可能需要手动调整权限"
        BAOTA_ENV="false"
    fi
    
    # 检查宝塔面板版本（如果可访问）
    if command -v bt &>/dev/null; then
        BAOTA_VERSION=$(bt 15 2>&1 | grep -oP 'v\d+\.\d+\.\d+')
        log_message "INFO" "宝塔面板版本: $BAOTA_VERSION"
    fi
    
    # 检查www用户
    if id "www" &>/dev/null; then
        log_message "INFO" "检测到www用户存在"
        WWW_USER="www"
        WWW_GROUP="www"
    else
        log_message "WARN" "未检测到www用户，使用当前用户: $(whoami)"
        WWW_USER="$(whoami)"
        WWW_GROUP="$(id -gn)"
    fi
}

# 检查系统环境
check_system_environment() {
    log_message "INFO" "开始系统环境检查..."
    
    # 检查操作系统
    OS_INFO=$(cat /etc/os-release 2>/dev/null | grep PRETTY_NAME | cut -d'"' -f2)
    if [ -z "$OS_INFO" ]; then
        OS_INFO=$(uname -a)
    fi
    log_message "INFO" "操作系统: $OS_INFO"
    
    # 检查Python版本
    if command -v python3 &> /dev/null; then
        PYTHON_VERSION=$(python3 --version 2>&1)
        log_message "INFO" "Python版本: $PYTHON_VERSION"
        
        # 检查是否满足最低版本要求
        python3 -c "import sys; sys.exit(0 if sys.version_info >= (3,7) else 1)" 2>/dev/null
        if [ $? -ne 0 ]; then
            log_message "ERROR" "Python版本低于3.7，需要3.7或更高版本"
            echo -e "${RED}❌ 错误: Python版本不满足要求${NC}"
            echo -e "${YELLOW}解决方案:${NC}"
            echo -e "  1. 在宝塔面板中安装Python 3.7+："
            echo -e "     - 打开宝塔面板 -> 软件商店 -> Python项目管理器"
            echo -e "     - 安装所需的Python 3.7+版本"
            echo -e "  2. 或者手动升级Python："
            echo -e "     - CentOS: yum -y install python37 python37-pip"
            echo -e "     - Ubuntu: apt-get update && apt-get install -y python3.7 python3.7-venv python3.7-pip"
            echo -e "${YELLOW}提示:${NC} 安装后请确保使用正确的Python路径"
            return 1
        fi
    else
        log_message "ERROR" "未找到python3命令，请确保Python 3.7+已安装"
        echo -e "${RED}❌ 错误: 未找到python3命令${NC}"
        echo -e "${YELLOW}解决方案:${NC}"
        echo -e "  1. 在宝塔面板中安装Python："
        echo -e "     - 打开宝塔面板 -> 软件商店 -> Python项目管理器"
        echo -e "     - 安装Python 3.7+版本"
        return 1
    fi
    
    # 检查pip版本
    if command -v pip3 &> /dev/null; then
        PIP_VERSION=$(pip3 --version 2>&1)
        log_message "INFO" "Pip版本: $PIP_VERSION"
    else
        log_message "ERROR" "未找到pip3命令，请确保pip已安装"
        return 1
    fi
    
    # 检查必要的系统命令
    for cmd in lsof ps grep awk kill chmod chown; do
        if ! command -v $cmd &> /dev/null; then
            log_message "ERROR" "缺少必要的系统命令: $cmd"
            return 1
        fi
    done
    
    log_message "SUCCESS" "系统环境检查通过"
    return 0
}

# 清理和创建Linux虚拟环境
setup_linux_venv() {
    log_message "INFO" "开始虚拟环境设置（Linux专用）..."
    
    # 宝塔环境特殊处理：优先使用宝塔Python项目管理器创建的虚拟环境
    if [ "$BAOTA_ENV" == "true" ]; then
        # 检查宝塔Python项目管理器常见的虚拟环境路径
        local bt_venv_path="$PROJECT_DIR/venv"
        if [ -d "$bt_venv_path" ] && [ -f "$bt_venv_path/bin/python3" ]; then
            log_message "INFO" "检测到宝塔Python项目管理器创建的虚拟环境: $bt_venv_path"
            VENV_DIR="$bt_venv_path"
            log_message "SUCCESS" "使用宝塔虚拟环境: $VENV_DIR"
        else
            log_message "INFO" "未检测到宝塔Python项目管理器创建的虚拟环境，将创建新的虚拟环境"
        fi
    fi
    
    # 检查是否存在Windows风格的虚拟环境
    if [ -d "$VENV_DIR" ] && [ -f "$VENV_DIR/Scripts/activate" ]; then
        log_message "WARN" "检测到Windows风格虚拟环境，需要重新创建Linux格式虚拟环境"
        
        # 备份requirements.txt
        if [ -f "requirements.txt" ]; then
            cp requirements.txt requirements.txt.bak
            log_message "INFO" "已备份requirements.txt"
        fi
        
        # 删除Windows风格虚拟环境
        log_message "INFO" "删除Windows风格虚拟环境..."
        rm -rf "$VENV_DIR"
        
        # 创建新的Linux虚拟环境
        log_message "INFO" "创建Linux风格虚拟环境..."
        python3 -m venv "$VENV_DIR"
        if [ $? -ne 0 ]; then
            log_message "ERROR" "创建虚拟环境失败"
            return 1
        fi
        
        # 恢复requirements.txt（如果有备份）
        if [ -f "requirements.txt.bak" ]; then
            mv requirements.txt.bak requirements.txt
            log_message "INFO" "已恢复requirements.txt"
        fi
    fi
    
    # 检查Linux虚拟环境是否存在
    if [ ! -d "$VENV_DIR" ] || [ ! -f "$VENV_DIR/bin/activate" ]; then
        log_message "INFO" "创建Linux虚拟环境..."
        python3 -m venv "$VENV_DIR"
        if [ $? -ne 0 ]; then
            log_message "ERROR" "创建虚拟环境失败"
            return 1
        fi
    fi
    
    # 设置虚拟环境权限
    log_message "INFO" "设置虚拟环境权限..."
    chmod -R 755 "$VENV_DIR"
    
    # 宝塔特定：设置www用户权限
    if [ "$BAOTA_ENV" == "true" ] && id "www" &>/dev/null; then
        chown -R www:www "$VENV_DIR"
        log_message "INFO" "已设置虚拟环境所有权为www:www"
    fi
    
    # 设置激活路径和gunicorn路径
    VENV_ACTIVATE="$VENV_DIR/bin/activate"
    GUNICORN_PATH="$VENV_DIR/bin/gunicorn"
    
    # 验证虚拟环境Python版本
    if [ -f "$VENV_DIR/bin/python3" ]; then
        local venv_python_version=$($VENV_DIR/bin/python3 --version 2>&1)
        log_message "INFO" "虚拟环境Python版本: $venv_python_version"
        
        # 检查虚拟环境Python版本是否满足要求
        $VENV_DIR/bin/python3 -c "import sys; sys.exit(0 if sys.version_info >= (3,7) else 1)" 2>/dev/null
        if [ $? -ne 0 ]; then
            log_message "ERROR" "虚拟环境Python版本低于3.7，需要3.7或更高版本"
            echo -e "${YELLOW}提示:${NC} 在宝塔面板中选择Python 3.7+版本创建虚拟环境"
            return 1
        fi
    fi
    
    log_message "SUCCESS" "虚拟环境设置完成"
    return 0
}

# 安装和更新依赖
install_dependencies() {
    log_message "INFO" "开始安装项目依赖..."
    
    # 激活虚拟环境
    if [ -f "$VENV_ACTIVATE" ]; then
        log_message "INFO" "激活虚拟环境: $VENV_ACTIVATE"
        source "$VENV_ACTIVATE"
        
        # 升级pip到最新版本
        log_message "INFO" "升级pip..."
        pip install --upgrade pip
        if [ $? -ne 0 ]; then
            log_message "ERROR" "pip升级失败"
            return 1
        fi
        
        # 检查并安装依赖
        if [ -f "requirements.txt" ]; then
            log_message "INFO" "安装requirements.txt中的依赖..."
            pip install -r requirements.txt -v >> "$DIAGNOSTIC_LOG" 2>&1
            if [ $? -ne 0 ]; then
                log_message "ERROR" "依赖安装失败，查看诊断日志了解详情"
                return 1
            fi
            log_message "INFO" "验证关键依赖安装状态..."
            
            # 验证关键依赖
            for pkg in flask gunicorn pymysql python-dotenv requests; do
                pip show "$pkg" &>/dev/null
                if [ $? -ne 0 ]; then
                    log_message "WARN" "依赖包 $pkg 似乎未正确安装，尝试单独安装..."
                    pip install "$pkg"
                else
                    log_message "INFO" "依赖包 $pkg 已安装"
                fi
            done
        else
            log_message "ERROR" "未找到requirements.txt文件"
            return 1
        fi
        
        log_message "SUCCESS" "依赖安装完成"
        return 0
    else
        log_message "ERROR" "虚拟环境激活脚本不存在: $VENV_ACTIVATE"
        return 1
    fi
}

# 检查环境变量配置
check_env_configuration() {
    log_message "INFO" "检查环境变量配置..."
    
    # 检查.env文件是否存在
    if [ ! -f "$PROJECT_DIR/.env" ]; then
        log_message "ERROR" "未找到.env文件，请根据.env.example创建"
        log_message "INFO" "创建.env示例文件..."
        cat > "$PROJECT_DIR/.env.example" << EOF
# 数据库配置 - 宝塔MySQL配置
DB_HOST=localhost
DB_PORT=3306
DB_USER=sms_user
DB_PASSWORD=your_password
DB_NAME=sms_verification

# 短信服务配置
SMS_API_KEY=your_sms_api_key
SMS_API_SECRET=your_sms_api_secret
SMS_SIGNATURE=短信签名
SMS_TEMPLATE_ID=短信模板ID

# 应用配置
APP_SECRET_KEY=your_app_secret_key
API_TOKEN=your_api_token

# 业务配置
MAX_MONTHLY_SENDS=100
MIN_SEND_INTERVAL=60
CODE_EXPIRATION=5
EOF
        log_message "WARN" "已创建.env.example模板，请复制为.env并配置实际值"
        return 1
    fi
    
    # 检查必要的环境变量
    local missing_vars=0
    local required_vars=("DB_HOST" "DB_PORT" "DB_USER" "DB_PASSWORD" "DB_NAME" "APP_SECRET_KEY" "API_TOKEN")
    
    for var in "${required_vars[@]}"; do
        if ! grep -q "^$var=" "$PROJECT_DIR/.env"; then
            log_message "ERROR" "缺少必要的环境变量: $var"
            missing_vars=1
        elif grep -q "^$var=your_" "$PROJECT_DIR/.env"; then
            log_message "WARN" "环境变量 $var 仍使用默认值，请修改"
        fi
    done
    
    # 设置.env文件权限为600（宝塔安全最佳实践）
    chmod 600 "$PROJECT_DIR/.env"
    log_message "INFO" "已设置.env文件权限为600"
    
    # 宝塔特定：设置www用户权限
    if [ "$BAOTA_ENV" == "true" ] && id "www" &>/dev/null; then
        chown www:www "$PROJECT_DIR/.env"
        log_message "INFO" "已设置.env文件所有权为www:www"
    fi
    
    if [ $missing_vars -eq 1 ]; then
        log_message "ERROR" "请修复环境变量配置后重试"
        return 1
    fi
    
    log_message "SUCCESS" "环境变量配置检查完成"
    return 0
}

# 停止现有进程
stop_existing_processes() {
    log_message "INFO" "检查并停止现有进程..."
    
    # 查找占用端口的进程
    if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
        local pids=$(lsof -Pi :$PORT -sTCP:LISTEN -t)
        log_message "WARN" "检测到端口 $PORT 被占用，进程ID: $pids"
        
        # 终止进程
        for pid in $pids; do
            log_message "INFO" "终止占用端口 $PORT 的进程 $pid"
            kill -9 "$pid" 2>/dev/null
            if [ $? -eq 0 ]; then
                log_message "INFO" "已终止进程 $pid"
            else
                log_message "ERROR" "无法终止进程 $pid"
            fi
        done
        sleep 2  # 等待进程终止
    else
        log_message "INFO" "端口 $PORT 未被占用"
    fi
    
    # 查找Gunicorn进程
    local gunicorn_pids=$(ps aux | grep '[g]unicorn.*src.wsgi' | awk '{print $2}')
    if [ ! -z "$gunicorn_pids" ]; then
        log_message "WARN" "检测到Gunicorn进程运行中，进程ID: $gunicorn_pids"
        
        # 终止Gunicorn进程
        for pid in $gunicorn_pids; do
            log_message "INFO" "终止Gunicorn进程 $pid"
            kill -9 "$pid" 2>/dev/null
            if [ $? -eq 0 ]; then
                log_message "INFO" "已终止Gunicorn进程 $pid"
            else
                log_message "ERROR" "无法终止Gunicorn进程 $pid"
            fi
        done
        sleep 2  # 等待进程终止
    else
        log_message "INFO" "未检测到Gunicorn进程"
    fi
    
    log_message "INFO" "进程清理完成"
}

# 测试Python模块导入
test_python_imports() {
    log_message "INFO" "测试Python模块导入..."
    
    # 激活虚拟环境
    source "$VENV_ACTIVATE"
    
    # 创建测试脚本
    cat > "$PROJECT_DIR/test_imports.py" << 'EOF'
try:
    # 测试Flask应用导入
    from src.wsgi import application
    print("✓ src.wsgi模块导入成功")
    
    # 测试数据库连接模块
    from src.db_helper import DBHelper
    print("✓ src.db_helper模块导入成功")
    
    # 测试短信服务模块
    from src.sms_service import SmsService
    print("✓ src.sms_service模块导入成功")
    
    # 测试助手模块
    from src.helpers import ComHelper
    print("✓ src.helpers模块导入成功")
    
    print("\n✓ 所有模块导入测试通过")
except Exception as e:
    print(f"✗ 模块导入失败: {str(e)}")
    import traceback
    traceback.print_exc()
    exit(1)
EOF
    
    # 运行测试脚本
    python3 "$PROJECT_DIR/test_imports.py" 2>&1 | tee -a "$DIAGNOSTIC_LOG"
    local import_status=$?
    
    # 清理测试脚本
    rm -f "$PROJECT_DIR/test_imports.py"
    
    if [ $import_status -eq 0 ]; then
        log_message "SUCCESS" "Python模块导入测试通过"
        return 0
    else
        log_message "ERROR" "Python模块导入测试失败"
        return 1
    fi
}

# 检查Gunicorn配置
check_gunicorn_config() {
    log_message "INFO" "检查Gunicorn配置..."
    
    # 激活虚拟环境
    source "$VENV_ACTIVATE"
    
    # 检查Gunicorn是否安装
    if ! command -v gunicorn &> /dev/null; then
        log_message "ERROR" "Gunicorn未安装，请重新安装依赖"
        return 1
    fi
    
    # 获取Gunicorn版本
    GUNICORN_VERSION=$(gunicorn --version 2>&1)
    log_message "INFO" "Gunicorn版本: $GUNICORN_VERSION"
    
    # 验证wsgi.py文件存在
    if [ ! -f "$PROJECT_DIR/src/wsgi.py" ]; then
        log_message "ERROR" "wsgi.py文件不存在，请检查项目结构"
        return 1
    fi
    
    # 检查wsgi.py内容
    if ! grep -q "application" "$PROJECT_DIR/src/wsgi.py"; then
        log_message "WARN" "wsgi.py可能缺少application变量定义，创建标准wsgi.py..."
        cat > "$PROJECT_DIR/src/wsgi.py" << 'EOF'
from .app import app

# Gunicorn需要的application变量
application = app
EOF
        chmod 644 "$PROJECT_DIR/src/wsgi.py"
        log_message "INFO" "已创建标准wsgi.py文件"
    fi
    
    log_message "SUCCESS" "Gunicorn配置检查完成"
    return 0
}

# 使用Gunicorn启动应用
start_application() {
    log_message "INFO" "使用Gunicorn启动应用..."
    
    # 激活虚拟环境
    source "$VENV_ACTIVATE"
    
    # 确保日志文件存在并设置权限
    touch "$GUNICORN_ERROR_LOG" "$GUNICORN_ACCESS_LOG"
    chmod 644 "$GUNICORN_ERROR_LOG" "$GUNICORN_ACCESS_LOG"
    
    # 宝塔特定：设置www用户权限
    if [ "$BAOTA_ENV" == "true" ] && id "www" &>/dev/null; then
        chown www:www "$GUNICORN_ERROR_LOG" "$GUNICORN_ACCESS_LOG"
    fi
    
    # 构建Gunicorn命令 - 宝塔Linux优化版
    GUNICORN_CMD="gunicorn"
    GUNICORN_OPTS=("")
    GUNICORN_OPTS+=("-w $WORKERS")  # 工作进程数
    GUNICORN_OPTS+=("-b 127.0.0.1:$PORT")  # 绑定地址和端口
    GUNICORN_OPTS+=("--chdir $PROJECT_DIR")  # 工作目录
    GUNICORN_OPTS+=("--timeout $TIMEOUT")  # 超时时间
    GUNICORN_OPTS+=("--worker-class sync")  # 工作进程类型
    GUNICORN_OPTS+=("--max-requests 1000")  # 最大请求数
    GUNICORN_OPTS+=("--max-requests-jitter 50")  # 最大请求数抖动
    GUNICORN_OPTS+=("--keep-alive 2")  # 保持连接时间
    GUNICORN_OPTS+=("--log-level info")  # 日志级别
    GUNICORN_OPTS+=("--error-logfile $GUNICORN_ERROR_LOG")  # 错误日志
    GUNICORN_OPTS+=("--access-logfile $GUNICORN_ACCESS_LOG")  # 访问日志
    GUNICORN_OPTS+=("--access-logformat '%(h)s %(l)s %(u)s %(t)s \"%(r)s\" %(s)s %(b)s \"%(f)s\" \"%(a)s\"'")  # 访问日志格式
    GUNICORN_OPTS+=("--daemon")  # 后台运行
    GUNICORN_OPTS+=("src.wsgi:application")  # WSGI入口
    
    log_message "INFO" "执行命令: $GUNICORN_CMD ${GUNICORN_OPTS[@]}"
    
    # 执行Gunicorn命令
    $GUNICORN_CMD "${GUNICORN_OPTS[@]}"
    local gunicorn_status=$?
    
    if [ $gunicorn_status -eq 0 ]; then
        log_message "INFO" "Gunicorn启动命令已执行"
        sleep 3  # 等待服务启动
        
        # 验证服务是否启动成功
        if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
            local pid=$(lsof -Pi :$PORT -sTCP:LISTEN -t)
            log_message "SUCCESS" "服务已在端口 $PORT 成功启动，进程ID: $pid"
            return 0
        else
            log_message "ERROR" "服务启动失败，端口 $PORT 未被监听"
            log_message "ERROR" "请检查错误日志: $GUNICORN_ERROR_LOG"
            return 1
        fi
    else
        log_message "ERROR" "Gunicorn启动命令执行失败，退出码: $gunicorn_status"
        return 1
    fi
}

# 设置项目文件权限
set_project_permissions() {
    log_message "INFO" "设置项目文件权限..."
    
    # 基本权限设置
    chmod -R 755 "$PROJECT_DIR"
    
    # 宝塔特定：设置www用户权限
    if [ "$BAOTA_ENV" == "true" ] && id "www" &>/dev/null; then
        chown -R www:www "$PROJECT_DIR"
        log_message "INFO" "已设置项目目录所有权为www:www"
    fi
    
    # 确保脚本可执行
    chmod +x "$0"
    
    # 确保Python文件权限正确
    find "$PROJECT_DIR" -name "*.py" -exec chmod 644 {} \;
    
    log_message "SUCCESS" "项目文件权限设置完成"
}

# 显示成功信息
display_success_info() {
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}🚀 短信验证平台启动成功！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo -e "${BLUE}🔧 运行信息:${NC}"
    echo -e "   - ${YELLOW}端口:${NC} ${PORT}"
    echo -e "   - ${YELLOW}工作进程:${NC} ${WORKERS}"
    echo -e "   - ${YELLOW}超时时间:${NC} ${TIMEOUT}秒"
    echo -e "   - ${YELLOW}虚拟环境:${NC} ${VENV_DIR}"
    echo -e "   - ${YELLOW}项目目录:${NC} ${PROJECT_DIR}"
    echo -e "${BLUE}📊 日志文件:${NC}"
    echo -e "   - ${YELLOW}诊断日志:${NC} ${DIAGNOSTIC_LOG}"
    echo -e "   - ${YELLOW}错误日志:${NC} ${GUNICORN_ERROR_LOG}"
    echo -e "   - ${YELLOW}访问日志:${NC} ${GUNICORN_ACCESS_LOG}"
    echo -e "${BLUE}🌐 访问地址:${NC} http://127.0.0.1:${PORT}"
    echo -e "${GREEN}========================================${NC}"
    echo -e "${YELLOW}⚠️  宝塔虚拟环境使用提示:${NC}"
    echo -e "  1. Supervisor配置命令:${NC}"
    echo -e "     ${GUNICORN_PATH} -w ${WORKERS} -b 127.0.0.1:${PORT} --chdir ${PROJECT_DIR} src.wsgi:application"
    echo -e "  2. 宝塔Python项目管理器集成:${NC}"
    echo -e "     - 打开宝塔面板 -> 软件商店 -> Python项目管理器"
    echo -e "     - 选择站点 -> 版本选择 3.7+ -> 安装依赖"
    echo -e "     - 映射路径: ${PROJECT_DIR}"
    echo -e "     - 启动方式: Gunicorn"
    echo -e "     - 启动文件: src/wsgi.py"
    echo -e "     - 端口: ${PORT}"
    echo -e "${GREEN}========================================${NC}"
}

# 主函数
main() {
    # 设置日志目录
    setup_log_directory
    
    # 检测宝塔环境
    detect_baota_environment
    
    # 执行系统环境检查
    if ! check_system_environment; then
        echo -e "${RED}❌ 系统环境检查失败，请查看详细日志: $DIAGNOSTIC_LOG${NC}"
        exit 1
    fi
    
    # 停止现有进程
    stop_existing_processes
    
    # 设置项目权限
    set_project_permissions
    
    # 设置Linux虚拟环境
    if ! setup_linux_venv; then
        echo -e "${RED}❌ 虚拟环境设置失败，请查看详细日志: $DIAGNOSTIC_LOG${NC}"
        exit 1
    fi
    
    # 安装依赖
    if ! install_dependencies; then
        echo -e "${RED}❌ 依赖安装失败，请查看详细日志: $DIAGNOSTIC_LOG${NC}"
        exit 1
    fi
    
    # 检查环境变量配置
    if ! check_env_configuration; then
        echo -e "${RED}❌ 环境变量配置检查失败，请查看详细日志: $DIAGNOSTIC_LOG${NC}"
        exit 1
    fi
    
    # 测试Python模块导入
    if ! test_python_imports; then
        echo -e "${RED}❌ Python模块导入测试失败，请查看详细日志: $DIAGNOSTIC_LOG${NC}"
        exit 1
    fi
    
    # 检查Gunicorn配置
    if ! check_gunicorn_config; then
        echo -e "${RED}❌ Gunicorn配置检查失败，请查看详细日志: $DIAGNOSTIC_LOG${NC}"
        exit 1
    fi
    
    # 启动应用
    if ! start_application; then
        echo -e "${RED}❌ 应用启动失败，请查看详细日志: $DIAGNOSTIC_LOG 和 $GUNICORN_ERROR_LOG${NC}"
        exit 1
    fi
    
    # 显示成功信息
    display_success_info
    
    echo -e "${GREEN}✅ 启动完成！${NC}"
}

# 执行主函数
main